package com.foodcommunity.controller;

import com.foodcommunity.common.Result;
import com.foodcommunity.dto.RestaurantReviewDTO;
import com.foodcommunity.entity.Restaurant;
import com.foodcommunity.entity.RestaurantReview;
import com.foodcommunity.entity.User;
import com.foodcommunity.service.RestaurantService;
import com.foodcommunity.utils.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/restaurants")
public class RestaurantController {

    @Autowired
    private RestaurantService restaurantService;

    /**
     * 获取热门餐厅
     */
    @GetMapping("/hot")
    public Result<List<Map<String, Object>>> getHotRestaurants() {
        List<Map<String, Object>> restaurants = restaurantService.getHotRestaurants();
        return Result.success(restaurants);
    }

    /**
     * 获取餐厅详情
     */
    @GetMapping("/{id}")
    public Result<Restaurant> getRestaurantDetail(@PathVariable Long id) {
        return restaurantService.getRestaurantDetail(id);
    }

    /**
     * 添加餐厅
     */
    @PostMapping
    public Result<Restaurant> addRestaurant(@Valid @RequestBody Restaurant restaurant, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }
        
        // 只允许 admin 用户添加餐厅
        if (!"admin".equals(user.getUsername())) {
            return Result.error("只有管理员可以添加餐厅");
        }
        
        return restaurantService.addRestaurant(restaurant);
    }

    /**
     * 更新餐厅
     */
    @PutMapping("/{id}")
    public Result<Restaurant> updateRestaurant(@PathVariable Long id, @Valid @RequestBody Restaurant restaurant, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }
        
        // 只允许 admin 用户更新餐厅
        if (!"admin".equals(user.getUsername())) {
            return Result.error("只有管理员可以更新餐厅");
        }
        
        restaurant.setId(id);
        return restaurantService.updateRestaurant(restaurant);
    }

    /**
     * 删除餐厅
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteRestaurant(@PathVariable Long id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }
        return restaurantService.deleteRestaurant(id);
    }

    /**
     * 分页获取餐厅列表
     */
    @GetMapping
    public Result<Map<String, Object>> getRestaurantsWithPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        Map<String, Object> result = restaurantService.getRestaurantsWithPage(page, size);
        return Result.success(result);
    }

    /**
     * 根据条件筛选餐厅
     */
    @GetMapping("/filter")
    public Result<Map<String, Object>> getRestaurantsByCondition(
            @RequestParam(required = false) String cuisineType,
            @RequestParam(required = false) Integer minPrice,
            @RequestParam(required = false) Integer maxPrice,
            @RequestParam(required = false) Double minRating,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        Map<String, Object> result = restaurantService.getRestaurantsByCondition(
                cuisineType, minPrice, maxPrice, minRating, page, size);
        return Result.success(result);
    }

    /**
     * 添加餐厅评论
     */
    @PostMapping("/reviews")
    public Result<RestaurantReview> addRestaurantReview(@Valid @RequestBody RestaurantReviewDTO reviewDTO, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }
        return restaurantService.addRestaurantReview(reviewDTO, user.getId());
    }

    /**
     * 删除餐厅评论
     */
    @DeleteMapping("/reviews/{id}")
    public Result<Void> deleteRestaurantReview(@PathVariable Long id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }
        return restaurantService.deleteRestaurantReview(id, user.getId());
    }

    /**
     * 获取餐厅评论列表
     */
    @GetMapping("/{restaurantId}/reviews")
    public Result<List<RestaurantReview>> getRestaurantReviews(@PathVariable Long restaurantId) {
        List<RestaurantReview> reviews = restaurantService.getRestaurantReviews(restaurantId);
        return Result.success(reviews);
    }

    /**
     * 分页获取餐厅评论
     */
    @GetMapping("/{restaurantId}/reviews/page")
    public Result<Map<String, Object>> getRestaurantReviewsWithPage(
            @PathVariable Long restaurantId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        Map<String, Object> result = restaurantService.getRestaurantReviewsWithPage(restaurantId, page, size);
        return Result.success(result);
    }

    /**
     * 获取用户的餐厅评论
     */
    @GetMapping("/reviews/user")
    public Result<List<RestaurantReview>> getUserRestaurantReviews(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }
        List<RestaurantReview> reviews = restaurantService.getUserRestaurantReviews(user.getId());
        return Result.success(reviews);
    }

    /**
     * 上传图片
     */
    @PostMapping("/upload-image")
    public Result<String> uploadImage(@RequestParam("file") MultipartFile file, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }
        
        if (file.isEmpty()) {
            return Result.error("请选择要上传的图片");
        }
        
        try {
            String imageUrl = FileUploadUtil.saveFile(file);
            return Result.success(imageUrl);
        } catch (Exception e) {
            return Result.error("图片上传失败: " + e.getMessage());
        }
    }
} 